package com.fc.example.adapter;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;

import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.nativead.unitgroup.api.CustomNativeAd;
import com.anythink.nativead.unitgroup.api.CustomNativeAdapter;
import com.fc.example.CustomApplication;
import com.yfanads.android.core.nat.YFAdNativeExpressAds;
import com.yfanads.android.core.nat.YFNativeExpressListener;
import com.yfanads.android.model.ExpView;
import com.yfanads.android.model.YFAdError;
import com.yfanads.android.utils.ScreenUtil;
import com.yfanads.android.utils.YFLog;
import com.yfanads.android.utils.YFUtil;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * 模板信息流适配器
 **/
public class YFNativeAdapter extends CustomNativeAdapter {
    String mUnitid = "";
    String appid = "";

    private static final String TAG = "YFNativeAdapter";

    YFAdNativeExpressAds easyNativeExpress;
    YFNativeView yfNativeView;
    private int width = 0;
    private int height = 0;

    @Override
    public void loadCustomNetworkAd(Context context, Map<String, Object> serverExtras, Map<String, Object> localExtra) {
        try {
            if (localExtra.containsKey(ATAdConst.KEY.AD_WIDTH)) {
                width = Integer.parseInt(Objects.requireNonNull(localExtra.get(ATAdConst.KEY.AD_WIDTH)).toString());
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        try {
            if (localExtra.containsKey(ATAdConst.KEY.AD_HEIGHT)) {
                height = Integer.parseInt(Objects.requireNonNull(localExtra.get(ATAdConst.KEY.AD_HEIGHT)).toString());
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (serverExtras.containsKey("appid") && serverExtras.containsKey("unitid")) {
            appid = (String) serverExtras.get("appid");
            mUnitid = (String) serverExtras.get("unitid");
            YFUtil.switchMainThread(() -> startLoadAds(context, null));
        } else {
            if (mLoadListener != null) {
                mLoadListener.onAdLoadError("", "appid or unitid is empty!");
            }
        }
    }

    @Override
    public boolean startBiddingRequest(Context context, Map<String, Object> serverExtras, Map<String, Object> localExtra, ATBiddingListener biddingListener) {
        try {
            if (localExtra.containsKey(ATAdConst.KEY.AD_WIDTH)) {
                width = Integer.parseInt(Objects.requireNonNull(localExtra.get(ATAdConst.KEY.AD_WIDTH)).toString());
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        try {
            if (localExtra.containsKey(ATAdConst.KEY.AD_HEIGHT)) {
                height = Integer.parseInt(Objects.requireNonNull(localExtra.get(ATAdConst.KEY.AD_HEIGHT)).toString());
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (serverExtras.containsKey("appid") && serverExtras.containsKey("unitid")) {
            appid = (String) serverExtras.get("appid");
            mUnitid = (String) serverExtras.get("unitid");
            YFUtil.switchMainThread(() -> startLoadAds(context, biddingListener));
        } else {
            if (mLoadListener != null) {
                mLoadListener.onAdLoadError("", "appid or unitid is empty!");
            }
        }
        YFLog.debug(TAG + " startBiddingRequest appid_" + appid + ",mUnitid_" + mUnitid);
        return true;
    }

    private void startLoadAds(Context context, ATBiddingListener biddingListener) {
        YFInit.init(CustomApplication.getInstance(), appid);
        easyNativeExpress = new YFAdNativeExpressAds(context.getApplicationContext(), new YFNativeExpressListener() {

            @Override
            public void onAdRenderSuccess(List<ExpView> list) {
                if (list == null || list.isEmpty()) {
                    YFLog.debug(TAG + " 加载feed广告成功，但没有返回数据");
                    if (mLoadListener != null) {
                        mLoadListener.onAdLoadError("", "ad list is empty!");
                    }
                } else {
                    YFLog.debug(TAG + " 加载feed广告成功");
                    ExpView expView = list.get(0);
                    yfNativeView = new YFNativeView(context, easyNativeExpress, expView);
                    long ecpm = easyNativeExpress.getEcpm();
                    if (biddingListener != null) {
                        YFLog.debug(TAG + " NativeAd ecpm : " + ecpm);
                        if (ecpm < 0) {
                            ecpm = 0;
                        }
                        //获取货币单位
                        ATAdConst.CURRENCY currency = ATAdConst.CURRENCY.RMB_CENT;
                        //用于标识此次竞价的唯一ID，可使用UUID或者时间戳
                        String token = UUID.randomUUID().toString();
                        biddingListener.onC2SBiddingResultWithCache(ATBiddingResult.success(ecpm, token, null, currency), yfNativeView);
                    } else {
                        if (mLoadListener != null) {
                            mLoadListener.onAdCacheLoaded(yfNativeView);
                        }
                    }
                }
            }

            @Override
            public void onAdSuccess() {
                YFLog.debug(TAG + " onAdSuccess");
                easyNativeExpress.showAds((Activity) context);
            }

            @Override
            public void onAdExposure() {
                YFLog.debug(TAG + " onAdExposure");
            }

            @Override
            public void onAdRenderFailed() {
                YFLog.debug(TAG + " onAdRenderFailed");
            }

            @Override
            public void onAdClicked() {
                YFLog.debug(TAG + " onAdClicked");
            }

            @Override
            public void onAdClosed() {
                YFLog.debug(TAG + " onAdClosed");
            }

            @Override
            public void onAdFailed(YFAdError fcAdError) {
                YFLog.debug(TAG + " onAdFailed " + fcAdError.toString());
                if (biddingListener != null) {
                    biddingListener.onC2SBiddingResultWithCache(ATBiddingResult.fail(fcAdError.msg), null);
                } else {
                    if (mLoadListener != null) {
                        mLoadListener.onAdLoadError(fcAdError.code, fcAdError.msg);
                    }
                }
            }

            @Override
            public void onAdExposure(ExpView expView) {
                YFLog.debug(TAG + " onAdExposure " + expView);
                if (yfNativeView != null) {
                    yfNativeView.notifyAdImpression();
                }
            }

            @Override
            public void onAdRenderFailed(ExpView expView) {
                YFLog.debug(TAG + " onAdRenderFailed " + expView);
            }

            @Override
            public void onAdClicked(ExpView expView) {
                YFLog.debug(TAG + " onAdClicked " + expView);
                if (yfNativeView != null) {
                    yfNativeView.notifyAdClicked();
                }
            }

            @Override
            public void onAdClosed(ExpView expView) {
                YFLog.debug(TAG + " onAdClosed " + expView);
                if (yfNativeView != null) {
                    yfNativeView.onAdClose();
                }
                if (yfNativeView != null) {
                    yfNativeView.notifyAdDislikeClick();
                }
            }

        });
        easyNativeExpress.setAdsNumbers(1);
        if (width == 0) {
            width = ScreenUtil.px2dip(context, ScreenUtil.getScreenWidth(context));
        }
        easyNativeExpress.setViewAcceptedSize(width, height);
        easyNativeExpress.loadOnly(mUnitid);
    }

    @Override
    public void destory() {
        YFLog.debug(TAG + " destroy ");
        if (yfNativeView != null) {
            yfNativeView.destroy();
        }
        yfNativeView = null;
    }

    @Override
    public String getNetworkPlacementId() {
        return mUnitid;
    }

    @Override
    public String getNetworkSDKVersion() {
        return YFInit.sdkVersion;
    }

    @Override
    public String getNetworkName() {
        return YFInit.networkName;
    }

    private static class YFNativeView extends CustomNativeAd {

        private final ExpView mExpressView;
        private YFAdNativeExpressAds easyNativeExpress;
        private final Context context;
        public YFNativeView(Context context, YFAdNativeExpressAds easyNativeExpress, ExpView expressView) {
            this.context = context;
            this.mExpressView = expressView;
            this.easyNativeExpress = easyNativeExpress;
        }

        @Override
        public boolean isNativeExpress() {
            return true;
        }

        @Override
        public void destroy() {
            super.destroy();
            if (easyNativeExpress != null) {
                easyNativeExpress.destroy();
            }
            easyNativeExpress = null;
        }

        public View getAdMediaView(Object... object) {
            if (mExpressView.getView() != null) {
                return mExpressView.getView();
            }
            FrameLayout layout = new FrameLayout(context);
            this.mExpressView.render(layout);
            return layout;
        }

        public void onAdClose() {
            try {
                if (mExpressView != null && mExpressView.getView() != null) {
                    ViewParent parent = mExpressView.getView().getParent();
                    if (parent instanceof ViewGroup) {
                        ((ViewGroup) parent).removeView(mExpressView.getView());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
